package com.example.braden.answergame.common.im;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.example.braden.answergame.common.Constant;
import com.example.braden.answergame.common.LogUtils;
import com.example.braden.answergame.common.utils.ToastUtil;
import com.example.braden.answergame.common.view.LoadingDialog;
import com.example.braden.answergame.modules.main.domain.BaseMessage;
import com.example.braden.answergame.modules.main.domain.GameOverEntity;
import com.example.braden.answergame.modules.main.domain.PropMessageEntity;
import com.example.braden.answergame.modules.main.domain.QuestionEntity;
import com.example.braden.answergame.modules.main.domain.UserPropInfo;
import com.example.braden.answergame.modules.main.domain.UserStatusEntity;
import com.google.gson.Gson;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMSdkConfig;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Created by braden on 2018/3/12.
 */

public class IMUtil implements TIMMessageListener, TIMConnListener {
    private Activity mContext;
    private TIMUserConfig timUserConfig;
    private IMMessageListener messageListener;
    private static final int QUESTION_MSG = 1;//下发题目消息
    private static final int ANSWER_MSG = 2;//下发答题状态消息
    private static final int PROP_MSG = 3;//下发道具使用消息
    private static final int OVER_MSG = 4;//下发答题结束消息
    private static final int USER_MSG = 5;//用户和道具信息
    private WorkHandler mWorkHandler;
    private TIMCallBack loginListener;
    private static int NET_STATUS = -1;//当前的网络状态，1表示断开链接，0表示正常
    private static int NETWORKDIS = 1;//网络断开
    private static int QUIT_APP = 2;//退出
    private static int CLOSE_DIALOG = 3;//关闭dialog
    private static int SHOW_DIALOG = 4;//显示dialog
    //Handler mHandler = new Handler() {
    //    @Override public void handleMessage(Message msg) {
    //        super.handleMessage(msg);
    //        switch (msg.what) {
    //            case IM_LOGIN_FAIL:
    //
    //                break;
    //            case IM_LOGIN_SUCCESS:
    //                LogUtils.e("登录成功");
    //                break;
    //            case JOIN_QUES_GROUP_FAILED:
    //
    //                break;
    //            case JOIN_QUES_GROUP_SUCCESS:
    //                LogUtils.e("加入成功");
    //                break;
    //        }
    //    }
    //};

    public static IMUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public static class SingletonHolder {
        private static final IMUtil INSTANCE = new IMUtil();
    }

    public void init(Activity context, TIMCallBack loginListener) {
        if (mContext == null) {
            this.mContext = context;
        }
        mWorkHandler = new WorkHandler(this, mContext);
        this.loginListener = loginListener;
        TIMSdkConfig mTIMSdkConfig = new TIMSdkConfig(Constant.APP_ID);
        mTIMSdkConfig.setServiceEnabled(false);
        mTIMSdkConfig.setConnectionListener(this);
        mTIMSdkConfig.setAccoutType(23571);
        TIMManager.getInstance().init(mContext, mTIMSdkConfig);
        if (timUserConfig == null) {
            timUserConfig = new TIMUserConfig();
        }
        timUserConfig.setUserStatusListener(new TIMUserStatusListener() {
            @Override
            public void onForceOffline() {
                //关闭该页面
                //finish();
                LogUtils.e("onForceOffline");
                ToastUtil.showShort("有人登录了您的账号，请退出重进");
            }

            @Override
            public void onUserSigExpired() {
                LogUtils.e("onUserSigExpired");
            }
        });
        TIMManager.getInstance().addMessageListener(this);
    }

    public void setMessageListener(IMMessageListener messageListener) {
        this.messageListener = messageListener;
    }

    public void login(String identifier, String userSig) {
        TIMManager.getInstance().login(identifier, userSig, timUserConfig, loginListener);
    }

    public void loginOut() {
        TIMManager.getInstance().removeMessageListener(this);
        TIMManager.getInstance().logout(logOutListener);
    }

    /**
     * 登出的回调
     */
    private TIMCallBack logOutListener = new TIMCallBack() {
        @Override
        public void onError(int i, String s) {
            LogUtils.e("退出失败");
        }

        @Override
        public void onSuccess() {
            LogUtils.e("IM退出成功");
        }
    };

    /**
     * 收到消息
     */
    @Override
    public boolean onNewMessages(List<TIMMessage> list) {
        for (int i = 0; i < list.size(); i++) {
            TIMElem element = list.get(i).getElement(0);
            TIMElemType type = element.getType();
            if (type == TIMElemType.Text) {
                String text = ((TIMTextElem) element).getText();
                BaseMessage entity = new Gson().fromJson(text, BaseMessage.class);
                LogUtils.e("onNewMessages-text:" + text);
                switch (entity.getType()) {
                    case QUESTION_MSG:
                        QuestionEntity questionEntity =
                                new Gson().fromJson(text, QuestionEntity.class);
                        if (!questionEntity.getBody().getRid().equals(Constant.ROOMID)
                                || !questionEntity.getBody().getGid().equals(Constant.GAME_ID)) {
                            //ToastUtil.showShort("该房间不存在，请退出重进！");
                            return false;
                        }
                        messageListener.onReceiveMessage(questionEntity);
                        break;
                    case ANSWER_MSG:
                        UserStatusEntity userStatusEntity =
                                new Gson().fromJson(text, UserStatusEntity.class);
                        if (!userStatusEntity.getBody().getRid().equals(Constant.ROOMID)
                                || !userStatusEntity.getBody().getGid().equals(Constant.GAME_ID)) {
                            //ToastUtil.showShort("该房间不存在，请退出重进！");
                            return false;
                        }
                        messageListener.onReceiveAnswer(userStatusEntity);
                        break;
                    case PROP_MSG:
                        PropMessageEntity propMessageEntity =
                                new Gson().fromJson(text, PropMessageEntity.class);
                        if (!propMessageEntity.getBody().getRid().equals(Constant.ROOMID)
                                || !propMessageEntity.getBody().getGid().equals(Constant.GAME_ID)) {
                            //ToastUtil.showShort("该房间不存在，请退出重进！");
                            return false;
                        }
                        messageListener.onReceiveProp(propMessageEntity);
                        break;
                    case OVER_MSG:
                        GameOverEntity gameOverEntity =
                                new Gson().fromJson(text, GameOverEntity.class);
                        if (!gameOverEntity.getBody().getRid().equals(Constant.ROOMID)) {
                            //ToastUtil.showShort("该房间不存在，请退出重进！");
                            return false;
                        }
                        messageListener.onReceiveOver(gameOverEntity);
                        break;
                    case USER_MSG:
                        UserPropInfo userPropInfo = new Gson().fromJson(text, UserPropInfo.class);
                        LogUtils.e("ROOMID:" + Constant.ROOMID);
                        if (!Constant.ROOMID.equals(userPropInfo.getBody().getRid())) {
                            ToastUtil.showShort("该房间不存在，请退出重进！");
                            return false;
                        }
                        Constant.GAME_ID = userPropInfo.getBody().getGameid();
                        LogUtils.e("Gameid:" + Constant.GAME_ID);
                        messageListener.onReceiverUser(userPropInfo);
                        break;
                }
            }
        }
        return false;
    }

    @Override
    public void onConnected() {
        LogUtils.e("onConnected");
        NET_STATUS = 0;
        mWorkHandler.sendEmptyMessage(CLOSE_DIALOG);
    }

    @Override
    public void onDisconnected(int i, String s) {
        LogUtils.e("onDisconnected");
        mWorkHandler.sendEmptyMessage(SHOW_DIALOG);
        NET_STATUS = 1;
    }

    @Override
    public void onWifiNeedAuth(String s) {
        LogUtils.e("onWifiNeedAuth");
    }

    private class WorkHandler extends Handler {
        WeakReference<IMUtil> ref;
        private Activity mContext;

        public WorkHandler(IMUtil util, Activity mContext) {
            super(Looper.getMainLooper());
            ref = new WeakReference<>(util);
            this.mContext = mContext;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == NETWORKDIS) {
                LoadingDialog.getInstance(mContext).showDialog("连接失败，即将退出");
                mWorkHandler.sendEmptyMessageDelayed(QUIT_APP, 2000);
            } else if (msg.what == QUIT_APP) {
                messageListener.onNetwokrDis();
            } else if (msg.what == CLOSE_DIALOG) {
                mWorkHandler.removeMessages(NETWORKDIS);
                LoadingDialog.getInstance(mContext).dismissDialog();
            } else if (msg.what == SHOW_DIALOG) {
                mWorkHandler.sendEmptyMessageDelayed(NETWORKDIS, 5000);
                LoadingDialog.getInstance(mContext).showDialog("网络异常，正在连接中...");
            }
        }
    }
}
